package com.water.expert.extraction.service;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.water.expert.extraction.exception.CustomValidationException;
import com.water.expert.extraction.repository.Expert;
import com.water.expert.extraction.repository.Extraction;
import com.water.expert.extraction.repository.ExtractionResult;
import com.water.expert.extraction.repository.ExtractionResultRepository;
import com.water.expert.extraction.repository.Profession;

@Service
public class ExtractionResultService {
	@Autowired
	ExpertService expertService;
	@Autowired
	ExtractionResultRepository extractionResultRepository;
	
	public List<ExtractionResult> findByExtractionId(Long extractionId){
		return extractionResultRepository.findByExtractionId(extractionId);
	}
	
	public Iterable<ExtractionResult> genExtractionResultByExtraction(Extraction extraction) {
		List<ExtractionResult> existResults = findByExtractionId(extraction.getId());
		if(!existResults.isEmpty()) {
			throw new CustomValidationException("已经抽取过专家，请查询。");
		}
		Profession currentProfession = extraction.getCurrentProfession();
		List<Expert> experts = expertService.getExpertByCurrentProfession(currentProfession);
		int selectionCount = extraction.getSelectionCount();
		if(selectionCount> experts.size()) {
			throw new CustomValidationException("没有足够的专家供抽取，现有符合专家的人数为"+experts.size());
		}
		
		// 生成抽取结果
		SecureRandom secureRandom = new SecureRandom();
        List<Integer> uniqueNumbers = IntStream.generate(() -> secureRandom.nextInt(selectionCount))
                                               .distinct()
                                               .limit(selectionCount)
                                               .boxed()
                                               .collect(Collectors.toList());
		List<Expert> list = new ArrayList<>(experts);
		int[] indices = uniqueNumbers.stream().mapToInt(Integer::intValue).toArray();
		List<Expert> selectedExperts = getElements(list,indices);
		List<ExtractionResult> results = selectedExperts.stream().map(selectedExpert->{
			ExtractionResult result = new ExtractionResult();
			result.setExpert(selectedExpert);
			result.setExtraction(extraction);
			return result;
		}).collect(Collectors.toList());
		return extractionResultRepository.saveAll(results);
	}
	
	private static <T> List<T> getElements(List<T> list, int... indices) {
	    return list.stream().filter(new IndexFilter<>(indices))
	            .collect(Collectors.toList());
	}

	// 辅助过滤器类
	static class IndexFilter<T> implements Predicate<T> {
	    private final int[] indices;
	    private int currentIndex = 0;

	    public IndexFilter(int... indices) {
	        this.indices = indices;
	        Arrays.sort(this.indices); // 确保索引按顺序查找
	    }

	    @Override
	    public boolean test(T item) {
	        return Arrays.binarySearch(indices, currentIndex++) >= 0;
	    }
	}
}
